package com.itheima.springbootwebtlias.controller;


import com.itheima.springbootwebtlias.pojo.Emp;
import com.itheima.springbootwebtlias.pojo.Result;
import com.itheima.springbootwebtlias.service.EmpService;
import com.itheima.springbootwebtlias.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
public class LoginController {
    @Autowired
    private EmpService empService;

    @PostMapping("/login")
    public Result login(@RequestBody Emp emp) {
        //1.接收请求参数: username, password
        //请求参数格式：json：RequestBody + 实体对象/ Map对象
        log.info("登录：请求参数：{}", emp);

        //2.调用业务层Service功能方法，登录
        Emp resultEmp = empService.checkLogin(emp);
        //3.封装响应数据
        Map map = new HashMap<>();
        map.put("id",resultEmp.getId());
        map.put("username",resultEmp.getUsername());
        map.put("name",resultEmp.getName());

        //4.登录成功，颁发JWT令牌
        String jwtToken = JwtUtils.generateJwt(map); //生成令牌

        map.put("token",jwtToken); //颁发令牌
        log.info("登录成功，颁发令牌：{}" , jwtToken);

        return Result.success(map);

    }
}
